package com.sky.controller.user;

import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author : jiang
 * @date : 2023/10/18 16:09
 */
@RestController("UserDishController")
@RequestMapping("/user/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String, List<DishVO>> redisTemplate;

    /**
     * 根据分类id查询菜品及其口味
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishVO>> getDishByCategoryId(Long categoryId) {
        //构造Redis中的key
        String key = "dish_" + categoryId;

        //先查找缓存是否有数据
        List<DishVO> dishList = redisTemplate.opsForValue().get(key);
        //缓存中存在数据 直接返回数据
        if (dishList != null && dishList.size() > 0) {
            return Result.success(dishList);
        }
        //缓存中不存在数据 查询数据库
        dishList = dishService.getDishByCategoryId(categoryId);
        //将查询到的数据存入缓存中
        redisTemplate.opsForValue().set(key, dishList);
        //返回数据
        return Result.success(dishList);
    }
}
